package buildtools;

import javax.vecmath.Vector3d;

import math.Spherical;

import component.AbstractComponent;
import component.Ball;
import component.ComponentFactory;
import component.Status;
import component.Structure;
import component.Tube;
import component.group.ComponentGroup;

public class BallConnector extends StructureBuilder {

	public BallConnector(Structure structure, ComponentFactory factory) {
		super(structure, factory);
	}
	
	private ComponentGroup findPossibleConnectionsForBall(Ball ball) {
		ComponentGroup group = new ComponentGroup();
		
		for (Ball b : Extractor.extractBalls(structure.getPermanentGeoGroup())) {
			if (this.canConnectBalls(ball, b))
				group.add(b);
		}
		return group;
	}

	
	public void makeTubeConnectionsForBall(Ball ball) {
		this.clearTemporary();
		ComponentGroup possible = findPossibleConnectionsForBall(ball);
		
		ComponentGroup tubes = new ComponentGroup();
		
		for (AbstractComponent b : possible.getComponents()) {
			Tube t = makeTube(ball, (Ball)b);
			if (t != null) {
				tubes.add(t);
			}
		}
		tubes.setStatus(Status.PLACEMENT | Status.TRANSPARENT);
		this.temporaryGroup = tubes;
	}
	
	private Tube makeTube(Ball b1, Ball b2) {
		Vector3d oVector = new Vector3d();
		oVector.sub(b2.getPos(), b1.getPos());
		System.out.println(oVector);
		Spherical orientation = new Spherical();
		orientation.setVector(oVector);
		
		Tube tube = factory.createTube(b1.getPos(), orientation);
		tube.setStatus(Status.INVISIBLE);
		structure.addTemporaryComponent(tube);
		if (tube.isValidPosition()) {
			return tube;
		} else {
			tube.dispose();
		}
		return null;
	}

	@Override
	public void temporaryClicked(AbstractComponent component) {
		structure.transferToPermanent(component);
		temporaryGroup.remove(component);
		component.setStatus(Status.NORMAL);
		if (temporaryGroup.isEmpty())
			clearTemporary();
		
		connector.connectToBall((Tube)component);
	}

}
